import { ProTable, ProColumns, ModalForm, ProForm, ProFormText } from '@ant-design/pro-components'
import { useState, FC, useEffect } from 'react'
import { useSelector, useDispatch } from 'dva'

import { history } from 'umi'
import useRequest from '@ahooksjs/use-request'
import studentMagServices from '@/services/studentManagement'
import {
  PlusOutlined,
  UploadOutlined,
  LeftCircleOutlined,
  LeftCircleTwoTone
} from '@ant-design/icons'
import { ACTIONS } from '@/models'
import styles from './index.less'

import { Button, PageHeader, Input, message, Form, Popconfirm, Upload, UploadProps } from 'antd'
import { allStudentData } from '@/services/studentManagement/types'
import courseMagServices from '@/services/courseManagement/index'
import e from 'express'

const StudentMag: FC = () => {
  const courseInfo = useSelector((state: any) => state.saveInfo)
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const formData = new FormData()
  const [fileList, setFileList] = useState([] as any)
  const [pageNum, setPageNum] = useState(1)
  const [isOpen, setIsOpen] = useState(false)
  const [isAddModal, setIsAddModal] = useState(false)
  const [isUpdateModal, setIsUpdateModal] = useState(false)
  const [studentData, setStudentData] = useState<allStudentData>()
  const [studentId, setStudentId] = useState('')
  const [update, setUpdate] = useState(0)
  const [searchText, setSearchText] = useState('')
  const pageSize = 10
  //获取所有学生信息
  const { data: allStudentList, run: getAllStudent } = useRequest(
    studentMagServices.getAllStudent,
    {
      manual: true,
      onSuccess: (res) => {
        console.log(res)
      }
    }
  )

  //删除学生
  const { run: deleteStudent } = useRequest(studentMagServices.deleteStudent, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功！')
      setUpdate(update + 1)
    }
  })
  //添加学生
  const { run: AddStudent } = useRequest(studentMagServices.addStudent, {
    manual: true,
    onSuccess: () => {
      message.success('添加成功')
      setUpdate(update + 1)
      setIsOpen(false)
      setIsAddModal(false)
    }
  })
  //修改学生信息
  const { run: updateStudent } = useRequest(studentMagServices.updateStudent, {
    manual: true,
    onSuccess: () => {
      message.success('修改成功！')
      setUpdate(update + 1)
      setIsOpen(false)
      setIsUpdateModal(false)
    }
  })
  //上传文件
  const { run: uploadFile } = useRequest(courseMagServices.uploadFile, {
    manual: true,
    onSuccess: () => {
      fileList.length = 0
    }
  })
  useEffect(() => {
    if (courseInfo.courseId == '') {
      history.push('./courseManagement')
      message.warn('请先选择要查看的课程！')
    } else {
      getAllStudent({
        courseId: courseInfo?.courseId,
        pageSize,
        page: pageNum,
        description: searchText
      })
    }
  }, [pageNum, searchText, update])
  //表头
  const columns: ProColumns<allStudentData>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
      align: 'center'
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: '学生学号',
      dataIndex: 'studentNumber',
      align: 'center'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      align: 'center'
    },
    {
      title: '年级',
      dataIndex: 'grade',
      align: 'center'
    },
    {
      title: '班级',
      dataIndex: 'clazz',
      align: 'center'
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, index, action) => [
        <a
          onClick={() => {
            dispatch({
              type: ACTIONS.saveInfo.studentInfo,
              payload: {
                studentId: record.id,
                studentName: record.name,
                studentSex: record.sex,
                studentNumber: record.studentNumber,
                studentGrade: record.grade,
                studentClass: record.clazz,
                studentPhoto: record.photoUrl
              }
            })
            history.push('./courseResearch')
          }}
          key="detail"
        >
          查看
        </a>,
        <a
          key="editable"
          onClick={() => {
            setIsOpen(true)
            setIsUpdateModal(true)
            setStudentData({ ...record })
          }}
        >
          修改
        </a>,
        <Popconfirm
          key="删除"
          title={`是否确认删除【${record.name}】这个学生？`}
          onConfirm={() => {
            deleteStudent({ id: record.id, courseId: courseInfo.courseId })
          }}
        >
          <a>删除</a>
        </Popconfirm>
      ]
    }
  ]
  const onSearch = (value: string) => {
    setSearchText(value)
  }
  const onSubmit = (values: any) => {
    const { name, clazz, grade, studentNumber, sex } = values
    if (isAddModal) {
      AddStudent({ courseId: courseInfo.courseId, name, clazz, grade, studentNumber, sex })
    } else {
      updateStudent({ name, clazz, grade, studentNumber, sex, id: studentData?.id })
    }
    if (fileList.length != 0) {
      uploadFile(formData as any)
    }
  }
  const props: UploadProps = {
    maxCount: 1,
    beforeUpload: (file) => {
      const size = file.size / 1024 / 1024 / 1024
      if (size > 2) {
        message.warning('文件大小超过2G！请重新上传！')
        return false
      } else {
        setFileList(file)
        return true
      }
    },
    customRequest: (file) => {
      formData.append('type', 'student')
      formData.append('file', file.file)
    }
  }
  return (
    <div className={styles.ContentStyle}>
      <div className={styles.header}>
        <PageHeader
          backIcon={<LeftCircleTwoTone />}
          onBack={() => history.push('./courseManagement')}
          title="学生管理"
          subTitle={`课程：${courseInfo.courseName}`}
          extra={[
            <Input.Search placeholder="请输入：姓名|学号" onSearch={onSearch} />,
            <Button
              type="primary"
              onClick={() => {
                setIsOpen(true)
                setIsAddModal(true)
              }}
            >
              <PlusOutlined />
              添加学生
            </Button>
          ]}
        ></PageHeader>
      </div>
      <div className={styles.showTable}>
        <ProTable<allStudentData>
          headerTitle={`学生人数：${allStudentList?.total}`}
          columns={columns}
          dataSource={allStudentList?.records}
          pagination={{
            total: allStudentList?.total,
            pageSize: allStudentList?.size,
            onChange: (pageNum) => {
              setPageNum(pageNum)
            }
          }}
          search={false}
        ></ProTable>
      </div>
      <div className={styles.AddModal}>
        <ModalForm
          layout="horizontal"
          open={isOpen}
          title="添加学生"
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setIsOpen(false)
              setIsAddModal(false)
              setIsUpdateModal(false)
            }
          }}
          form={form}
          autoFocusFirstInput
          onFinish={async (values) => onSubmit(values)}
        >
          <ProForm.Group title="基本信息">
            <ProFormText
              name={'name'}
              label="学生姓名"
              initialValue={isUpdateModal ? studentData?.name : ''}
              rules={[{ required: true, message: '不能为空！' }]}
            ></ProFormText>
            <ProFormText
              name={'sex'}
              label="性别"
              initialValue={isUpdateModal ? studentData?.sex : ''}
              rules={[{ required: true, message: '不能为空！' }]}
            ></ProFormText>
            <ProFormText
              name={'studentNumber'}
              label="学生学号"
              initialValue={isUpdateModal ? studentData?.studentNumber : ''}
              rules={[{ required: true, message: '不能为空！' }]}
            ></ProFormText>
            <ProFormText
              name={'grade'}
              label="年级"
              placeholder={'例：2020级'}
              initialValue={isUpdateModal ? studentData?.grade : ''}
              rules={[{ required: true, message: '不能为空！' }]}
            ></ProFormText>
            <ProFormText
              name={'clazz'}
              label="班级"
              placeholder={'例：电信二班'}
              initialValue={isUpdateModal ? studentData?.clazz : ''}
              rules={[{ required: true, message: '不能为空！' }]}
            ></ProFormText>
          </ProForm.Group>
          <ProForm.Group title="上传学生照片">
            <Upload {...props}>
              <Button>
                <UploadOutlined />
                点击上传
              </Button>
            </Upload>
          </ProForm.Group>
        </ModalForm>
      </div>
    </div>
  )
}
export default StudentMag
